package org.flyking.tool;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.flyking.data.Requirement;

import java.util.ArrayList;
import java.util.List;

public class RequirementListener implements ReadListener {
    private static final Logger logger = LogManager.getLogger(RequirementListener.class);
    private static final int BATCH_SIZE = 200; // 每200行处理一次
    private final List<Requirement> cachedList = new ArrayList<>();
    private final List<Requirement> totalList = new ArrayList<>(); // 最终结果集

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        cachedList.add((Requirement) o);
        // 分批缓存清理，防止OOM
        if (cachedList.size() >= BATCH_SIZE) {
            totalList.addAll(cachedList);
            cachedList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 读取完成后处理剩余数据
        if (!cachedList.isEmpty()) {
            totalList.addAll(cachedList);
            cachedList.clear();
        }
        logger.info("Excel读取完成，共读取: " + totalList.size() + " 条数据");
    }

    public List<Requirement> getTotalList() {
        return totalList;
    }
}
